<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <div th:replace="./widget/base"></div>
</head>
<body>

<div class="easyui-layout" data-options="fit:true">
    <div data-options="region:'west',split:true" style="width:40%">

        <div id="dictionaryCategoryToolbar">
            <a th:if="${#authorization.expression('hasRole('''+ SYSTEM_ADMIN +''') OR hasAuthority(''/COMPONENT/SYSTEM/DICTIONARY/PAGE_ALL/DICTIONARY_CATEGORY_ADD_DIALOG'')')}"
               href="javascript:" class="easyui-linkbutton" iconCls="fa fa-plus" plain="true"
               onclick="dictionaryCategoryAddDialog();">新增</a>

            <a th:if="${#authorization.expression('hasRole('''+ SYSTEM_ADMIN +''') OR hasAuthority(''/COMPONENT/SYSTEM/DICTIONARY/PAGE_ALL/DICTIONARY_CATEGORY_EDIT_DIALOG'')')}"
               href="javascript:" class="easyui-linkbutton" iconCls="fa fa-edit" plain="true"
               onclick="dictionaryCategoryEditDialog();">编辑</a>

            <a th:if="${#authorization.expression('hasRole('''+ SYSTEM_ADMIN +''') OR hasAuthority(''/COMPONENT/SYSTEM/DICTIONARY/PAGE_ALL/DICTIONARY_CATEGORY_DELETE_ALL'')')}"
               href="javascript:" class="easyui-linkbutton" iconCls="fa fa-close" plain="true"
               onclick="dictionaryCategoryDeleteAll();">删除</a>

            <a th:if="${#authorization.expression('hasRole('''+ SYSTEM_ADMIN +''') OR hasAuthority(''/COMPONENT/SYSTEM/DICTIONARY/PAGE_ALL/DICTIONARY_CATEGORY_EXPORT_ALL'')')}"
               href="javascript:" class="easyui-linkbutton" iconCls="fa fa-download" plain="true"
               onclick="dictionaryCategoryExportAll();">导出</a>

            <span th:if="${#authorization.expression('hasRole('''+ SYSTEM_ADMIN +''') OR hasAuthority(''/COMPONENT/SYSTEM/DICTIONARY/PAGE_ALL/DICTIONARY_CATEGORY_IMPORT_ALL'')')}">
                <label>导入：</label><input id="file" class="easyui-filebox" style="width:200px" data-options="buttonText:'选择文件'"> <a href="javascript:" class="easyui-linkbutton" iconCls="fa fa-upload" plain="true" id="uploadButton">立即导入</a>
            </span>

        </div>

        <table id="dictionaryCategory"></table>

    </div>

    <div data-options="region:'center',split:true">
        <div id="dictionaryToolbar">
            <a th:if="${#authorization.expression('hasRole('''+ SYSTEM_ADMIN +''') OR hasAuthority(''/COMPONENT/SYSTEM/DICTIONARY/PAGE_ALL/DICTIONARY_ADD_DIALOG'')')}"
               href="javascript:" class="easyui-linkbutton" iconCls="fa fa-plus" plain="true"
               onclick="dictionaryAddDialog();">新增</a>

            <a th:if="${#authorization.expression('hasRole('''+ SYSTEM_ADMIN +''') OR hasAuthority(''/COMPONENT/SYSTEM/DICTIONARY/PAGE_ALL/DICTIONARY_COPY_ADD_DIALOG'')')}"
               href="javascript:" class="easyui-linkbutton" iconCls="fa fa-edit" plain="true"
               onclick="dictionaryCopyAddDialog();">复制新增</a>

            <a th:if="${#authorization.expression('hasRole('''+ SYSTEM_ADMIN +''') OR hasAuthority(''/COMPONENT/SYSTEM/DICTIONARY/PAGE_ALL/DICTIONARY_EDIT_DIALOG'')')}"
               href="javascript:" class="easyui-linkbutton" iconCls="fa fa-edit" plain="true"
               onclick="dictionaryEditDialog();">编辑</a>

            <a th:if="${#authorization.expression('hasRole('''+ SYSTEM_ADMIN +''') OR hasAuthority(''/COMPONENT/SYSTEM/DICTIONARY/PAGE_ALL/DICTIONARY_DELETE_ALL'')')}"
               href="javascript:" class="easyui-linkbutton" iconCls="fa fa-close" plain="true"
               onclick="dictionaryDeleteAll();">删除</a>

            <a th:if="${#authorization.expression('hasRole('''+ SYSTEM_ADMIN +''') OR hasAuthority(''/COMPONENT/SYSTEM/DICTIONARY/PAGE_ALL/SYNC_TO_MEMORY'')')}"
               href="javascript:" class="easyui-linkbutton" iconCls="fa fa-refresh" plain="true"
               onclick="syncToMemory();">同步所有字典到内存</a>

        </div>
        <table id="dictionary"></table>
    </div>
</div>

<script type="text/javascript">
    $(function () {
        var columns = [
            {field: 'checkbox', checkbox: true},
            {field: 'id', title: 'ID'},
            {field: 'name', title: '分类名称'},
            {field: 'sort', title: '排序'},
            {field: 'remark', title: '备注'},
            {field: 'gmtModified', title: '更新时间'},
            {field: 'gmtCreated', title: '创建时间'}
        ];
        $('#dictionaryCategory').treegrid(expressui.grid.create, {
            title: '字典分类',
            url: Api.System.DICTIONARY_CATEGORY + '/page_all_parent',
            expandUrl: Api.System.DICTIONARY_CATEGORY + '/list_all_by_parent_id/{id}',
            columns: [columns],
            onCheck: function (row) {
                if (row) {
                    $('#dictionary').datagrid('reload', Api.System.DICTIONARY + '/page_all_by_dictionary_category_id/' + row.id);
                }
            },
            onUncheck: function (index, row) {
                $('#dictionary').datagrid('loadData', []);
            }
        });

        var IS_OR_NOT = [];
        expressui.ajax({
            url: Api.System.DICTIONARY + '/list_all_by_key/IS_OR_NOT',
            async: false,
            success: function (data) {
                if (data) {
                    IS_OR_NOT = data;
                }
            }
        });

        columns = [
            {field: 'checkbox', checkbox: true},
            {field: 'id', title: 'ID'},
            {field: 'keyName', title: '字典键名'},
            {field: 'key', title: '字典键'},
            {field: 'valueName', title: '字典值名'},
            {field: 'valueSlug', title: '字典值别名'},
            {field: 'value', title: '字典值'},
            {
                field: 'enable', title: '是否有效', formatter: function (value, row, index) {
                    return expressui.grid.formatter(value, IS_OR_NOT);
                }
            },
            {field: 'sort', title: '排序'},
            {field: 'remark', title: '备注'},
            {field: 'gmtModified', title: '更新时间'},
            {field: 'gmtCreated', title: '创建时间'}
        ];
        $('#dictionary').datagrid(expressui.grid.create, {
            title: '数据字典',
            columns: [columns]
        });
    });

    function dictionaryCategoryAddDialog() {
        var one = $('#dictionaryCategory').treegrid(expressui.grid.getCheckedOneOrMoreShowAlert);
        if (!one) {
            return;
        }

        $('#dictionaryCategoryAddDialog').dialog(expressui.dialog.create, {
            title: '新增字典分类',
            grid: {type: 'treegrid', selector: '#dictionaryCategory'},
            href: Page.System.DICTIONARY_CATEGORY + '/add_dialog',
            save: {
                url: Api.System.DICTIONARY_CATEGORY + '/add_one',
                data: one ? {parentId: one.id} : {},
                method: 'post'
            },
            buttons: [{
                text: '保存',
                iconCls: 'fa fa-save',
                handler: expressui.dialog.add,
                reload: [{type: 'treegrid', selector: '#dictionaryCategory'}, {
                    type: 'datagrid',
                    selector: '#dictionary',
                    data: []
                }],
                success: '新增成功'
            }, {
                text: '关闭',
                iconCls: 'fa fa-close',
                handler: expressui.dialog.close
            }]
        });
    }

    function dictionaryCategoryEditDialog() {
        var one = $('#dictionaryCategory').treegrid(expressui.grid.getCheckedOneShowAlert);
        if (!one) {
            return;
        }

        $('#dictionaryCategoryEditDialog').dialog(expressui.dialog.create, {
            title: '编辑字典分类',
            grid: {type: 'treegrid', selector: '#dictionaryCategory'},
            href: Page.System.DICTIONARY_CATEGORY + '/edit_dialog',
            get: {url: Api.System.DICTIONARY_CATEGORY + '/one/{id}', method: 'get'},
            save: {url: Api.System.DICTIONARY_CATEGORY + '/save_one', method: 'post'},
            buttons: [{
                text: '保存',
                iconCls: 'fa fa-save',
                handler: expressui.dialog.save,
                reload: [{type: 'treegrid', selector: '#dictionaryCategory'}, {
                    type: 'datagrid',
                    selector: '#dictionary',
                    data: []
                }],
                success: '保存成功'
            }, {
                text: '关闭',
                iconCls: 'fa fa-close',
                handler: expressui.dialog.close
            }]
        });
    }

    function dictionaryCategoryDeleteAll() {
        $('#dictionaryCategory').treegrid(expressui.grid.deleteRows, {
            url: Api.System.DICTIONARY_CATEGORY + '/delete_all',
            method: 'post',
            success: '删除成功',
            reload: [{type: 'treegrid', selector: '#dictionaryCategory'}, {
                type: 'datagrid',
                selector: '#dictionary',
                data: []
            }]
        });
    }

    function dictionaryCategoryExportAll() {
        var checked = $('#dictionaryCategory').treegrid('getChecked');
        var id = [];
        if(checked && checked.length>0) {
            for (var i = 0; i < checked.length; i++) {
                id.push(checked[i].id);
            }
            window.open(Api.System.DICTIONARY + '/export_all_by_dictionary_category_id_list?id=' + id)
        }
    }

    $('#uploadButton').click(function () {

        var one = $('#dictionaryCategory').treegrid(expressui.grid.getCheckedOneShowAlert);
        if (!one) {
            return;
        }

        if(!window._ajaxing) {
            window._ajaxing = upload(one);
        } else {
            $.messager.progress('正在上传...');
            window._ajaxing.abort();
            window._ajaxing = undefined;
        }
        if(window._ajaxing) {
            $(this).linkbutton({text: '取消', iconCls: 'fa fa-close'});
        } else {
            $(this).linkbutton({text: '立即导入', iconCls: 'fa fa-upload'});
        }
    });

    function upload(one) {
        var formData = new FormData();
        var file = $('#file').filebox('files')[0];
        formData.append('categoryId', one.id);
        formData.append('file', file);
        return $.ajax({
            url: Api.System.DICTIONARY + '/import_all_by_dictionary_category_id',
            type: 'post',
            data: formData,
            processData: false, // 不要对data参数进行序列化处理，默认为true
            contentType: false, // 不要设置Content-Type请求头，因为文件数据是以 multipart/form-data 来编码
            xhr: function () {
                var xhr = $.ajaxSettings.xhr();
                if (xhr.upload) {
                    xhr.upload.addEventListener('progress', function (e) {
                        if (e.lengthComputable) {
                            var total = e.total;
                            var position = e.loaded || e.position;
                            var percent = Math.ceil(position * 100 / total);
                            if (percent === 100) {
                                // progress.progressbar({text: '正在保存，请稍等...100%', value: 100});
                            }
                        }
                    }, false);
                }
                return xhr;
            },
            success: function (res, statusText, xhr) {
                if (res && res.code) {
                    // progress.progressbar('setValue', 0);
                    // progress.progressbar({text: '上传失败：0%', value: 0});
                    $.messager.alert('信息', res.message, 'error');
                } else {
                    if (xhr.readyState === 4) {
                        // progress.progressbar('setValue', 0);
                        // progress.progressbar({text: '未开始：0%', value: 0});
                        $('#file').filebox('clear');
                        $.messager.show({title: '信息', msg: '上传成功'});
                        $('#dictionary').datagrid('reload');
                    }
                }
                $('#uploadButton').linkbutton({text: '立即导入', iconCls: 'fa fa-upload'});
                window._ajaxing= undefined;
                $.messager.progress('close');
            },
            error: function (res) {
                if(res.responseJSON) {
                    $.messager.alert('信息', res.responseJSON.message, 'error');
                }
                $('#uploadButton').linkbutton({text: '立即导入', iconCls: 'fa fa-upload'});
                window._ajaxing= undefined;
                $.messager.progress('close');
            }
        });
    }

    function dictionaryAddDialog() {
        var one = $('#dictionaryCategory').treegrid(expressui.grid.getCheckedOneShowAlert);
        if (!one) {
            return;
        }

        $('#dictionaryAddDialog').dialog(expressui.dialog.create, {
            title: '新增字典',
            grid: {type: 'treegrid', selector: '#dictionaryCategory'},
            href: Page.System.DICTIONARY + '/add_dialog',
            save: {
                url: Api.System.DICTIONARY + '/add_one',
                data: {dictionaryCategoryId: '{id}'},
                method: 'post'
            },
            buttons: [{
                text: '保存',
                iconCls: 'fa fa-save',
                handler: expressui.dialog.add,
                reload: [{type: 'datagrid', selector: '#dictionary'}],
                success: '新增成功'
            }, {
                text: '关闭',
                iconCls: 'fa fa-close',
                handler: expressui.dialog.close
            }]
        });
    }

    function dictionaryCopyAddDialog() {
        var dictionaryCategory = $('#dictionaryCategory').datagrid(expressui.grid.getCheckedOneShowAlert);
        if (!dictionaryCategory) {
            return;
        }

        $('#dictionaryCopyAddDialog').dialog(expressui.dialog.create, {
            title: '复制新增字典',
            grid: {type: 'datagrid', selector: '#dictionary'},
            href: Page.System.DICTIONARY + '/add_dialog',
            get: {url: Api.System.DICTIONARY + '/one/{id}', method: 'get'},
            save: {
                url: Api.System.DICTIONARY + '/add_one',
                method: 'post',
                data: {dictionaryCategoryId: dictionaryCategory.id}
            },
            buttons: [{
                text: '复制新增',
                iconCls: 'fa fa-save',
                handler: expressui.dialog.save,
                reload: [{type: 'datagrid', selector: '#dictionary'}],
                success: '新增成功'
            }, {
                text: '关闭',
                iconCls: 'fa fa-close',
                handler: expressui.dialog.close
            }]
        });
    }

    function dictionaryEditDialog() {
        var one = $('#dictionary').datagrid(expressui.grid.getCheckedOneShowAlert);
        if (!one) {
            return;
        }

        $('#dictionaryEditDialog').dialog(expressui.dialog.create, {
            title: '编辑字典',
            grid: {type: 'datagrid', selector: '#dictionary'},
            href: Page.System.DICTIONARY + '/edit_dialog',
            get: {url: Api.System.DICTIONARY + '/one/{id}', method: 'get'},
            save: {url: Api.System.DICTIONARY + '/save_one', method: 'post'},
            buttons: [{
                text: '保存',
                iconCls: 'fa fa-save',
                handler: expressui.dialog.save,
                reload: [{type: 'datagrid', selector: '#dictionary'}],
                success: '保存成功'
            }, {
                text: '关闭',
                iconCls: 'fa fa-close',
                handler: expressui.dialog.close
            }]
        });
    }

    function dictionaryDeleteAll() {
        $('#dictionary').datagrid(expressui.grid.deleteRows, {
            url: Api.System.DICTIONARY + '/delete_all',
            method: 'post',
            success: '删除成功',
            reload: {type: 'datagrid', selector: '#dictionary'}
        });
    }

    function syncToMemory() {
        $.messager.confirm('信息', '确定继续操作吗？', function (ok) {
            if(ok) {
                expressui.ajax({
                    url: Api.System.DICTIONARY + '/sync_to_memory',
                    type: 'post',
                    success: function (data) {
                        $.messager.show({title: '信息', msg: '操作成功'});
                    },
                    error: function (XMLHttpRequest) {
                            if(XMLHttpRequest.status === 200) {
                                $.messager.show({title: '信息', msg: '操作成功'});
                            } else {
                                $.messager.show({title: '信息', msg: XMLHttpRequest.responseJSON.message});
                            }
                    }
                });
            }
        });
    }

</script>
</body>
</html>